// 2013-7-30下午12:29:47  net.betou.trade.admin.action.VideoAct.java

package net.betou.trade.admin.action;

import static net.betou.common.page.SimplePage.cpn;
import static net.betou.common.page.SimplePage.cpnPageSize;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.betou.common.image.ImageUtils;
import net.betou.common.page.Pagination;
import net.betou.common.upload.FileRepository;
import net.betou.common.util.DataCheckUtils;
import net.betou.common.util.TradeUtils;
import net.betou.common.web.Constants;
import net.betou.common.web.ResponseUtils;
import net.betou.core.service.FlashSpiderService;
import net.betou.trade.action.abs.ActionSupport;
import net.betou.trade.entity.main.AgentAndAdmins;
import net.betou.trade.entity.main.Video;
import net.betou.trade.main.manager.VideoMng;
import net.betou.trade.web.Messages;
import net.betou.trade.web.ResponseUtil;
import net.betou.trade.web.WebErrors;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 视频
 * 
 * @author 叶装装
 */
@Controller
public class VideoAct extends ActionSupport< Video >{
	private static final String DIRECTORY = "video";
	private static final Logger log = LoggerFactory.getLogger( VideoAct.class );

	@RequestMapping( "/video/v_list.jspx" )
	public String list( Integer pageSize, Integer pageNo, String searchProperty, String searchValue, String orderProperty, String orderDirection, HttpServletRequest request, HttpServletResponse response, ModelMap model ) {

		pageSize = cpnPageSize( pageSize );
		pageNo = cpn( pageNo );

		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		Pagination pagination = manager.getPage( admin, searchProperty, searchValue, orderProperty, orderDirection, pageNo, pageSize );

		model.addAttribute( "admin", admin );
		paramToModel( model, pagination, null, pageSize, searchProperty, searchValue, orderProperty, orderDirection, null );

		return getListPage( );
	}

	@RequestMapping( "/video/v_add.jspx" )
	public String v_add( HttpServletRequest request, ModelMap model ) {

		WebErrors errors = validateToSave( request );

		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}

		return getAddPage( );
	}

	@RequestMapping( "/video/o_save.jspx" )
	public String o_save( Video bean, HttpServletRequest request, HttpServletResponse response, ModelMap model ) {

		WebErrors errors = validateSave( bean );

		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}

		AgentAndAdmins admin = TradeUtils.getAdmin( request ); // 获取当前管理员

		bean = manager.save( bean, admin );

		logMng.operating( 0, request, Messages.LOG_VIDEO, "id=" + bean.getId( ) + ",title=" + bean.getTitle( ) );

		return "redirect:v_list.jspx";
	}

	@RequestMapping( "/video/v_edit.jspx" )
	public String v_edit( Integer id, HttpServletRequest request, ModelMap model ) {

		WebErrors errors = validateUpdate( request, id );

		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}

		Video bean = manager.findById( id );

		model.addAttribute( "bean", bean );

		return getUpdatePage( );
	}

	@RequestMapping( "/video/o_update.jspx" )
	public String o_update( Integer id, Video bean, HttpServletRequest request, ModelMap model ) {

		AgentAndAdmins admin = TradeUtils.getAdmin( request ); // 获取当前管理员

		WebErrors errors = validateOUpdate( request, id, admin.getId( ), admin.getSystem( ) );

		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}

		bean = manager.update( bean );

		logMng.operating( 1, request, Messages.LOG_VIDEO, "id=" + bean.getId( ) + ",title=" + bean.getTitle( ) );

		return "redirect:v_list.jspx";
	}

	@RequestMapping( "/video/o_delete.jspx" )
	public void o_delete( Integer [ ] ids, HttpServletResponse response, HttpServletRequest request ) {

		AgentAndAdmins admin = TradeUtils.getAdmin( request ); // 获取当前管理员

		ResponseUtil util = validateDelete( ids, admin.getId( ), admin.getSystem( ), response, request );

		if( util.hasResponse( ) ){
			util.renderJson( );
			return;
		}

		Video [ ] beans = manager.deleteByIds( ids );

		for ( Video bean : beans ){
			log.info( "delete Video id={}", bean.getId( ) );
			logMng.operating( 2, request, Messages.LOG_VIDEO, "id=" + bean.getId( ) + ",title=" + bean.getTitle( ) );
		}

		util.addSuccessResponse( Messages.getDeleteSuccessMessage( beans.length ) );

		util.renderJson( );
		return;

	}

	@RequestMapping( "/video/v_flash.jspx" )
	public void youkuFlash( String url, HttpServletRequest request, HttpServletResponse response, ModelMap model ) {

		ResponseUtil util = ResponseUtil.create( response );

		if( StringUtils.isBlank( url ) ){
			util.addErrorResponse( Messages.VIDEO_DO_NOT_GET_ADDRESS );
			util.renderJson( );
			return;
		}

		String address = youku.getSwfAddress( url );

		if( StringUtils.isBlank( address ) ){
			util.addErrorResponse( Messages.VIDEO_DO_NOT_GET_ADDRESS );
			util.renderJson( );
			return;
		}

		util.addSuccessResponse( address );
		util.renderJson( );
	}

	@RequestMapping( value = "/video/o_upload.jspx", method = RequestMethod.POST )
	public void o_upload( @RequestParam( value = "Filedata", required = false ) MultipartFile file, HttpServletRequest request, HttpServletResponse response, ModelMap model ) throws IllegalStateException, IOException {
		responseInit( response );

		MultipartHttpServletRequest multipartRequest = ( MultipartHttpServletRequest ) request;

		MultipartFile uplFile = multipartRequest.getFileMap( ).entrySet( ).iterator( ).next( ).getValue( );

		String filename = FilenameUtils.getName( uplFile.getOriginalFilename( ) );

		log.debug( "Parameter NewFile: {}", filename );

		String ext = FilenameUtils.getExtension( filename );

		if( !DataCheckUtils.isImage( ext ) || !ImageUtils.isImage( uplFile.getInputStream( ) ) ){
			ResponseUtils.render( response, "!" + Messages.FILE_ILEEAGE );
			return;
		}

		String fileUrl = fileRepository.storeByExt( Constants.UPLOAD_DIRECTORY, ext, uplFile );
		ResponseUtils.render( response,  fileUrl );
		return;
	}

	private void responseInit( HttpServletResponse response ) {
		response.setCharacterEncoding( "UTF-8" );
		response.setContentType( "text/html" );
		response.setHeader( "Cache-Control", "no-cache" );
	}

	private ResponseUtil validateDelete( Integer [ ] ids, Integer selfId, Boolean system, HttpServletResponse response, HttpServletRequest request ) {
		ResponseUtil util = ResponseUtil.create( response );

		if( ids == null || ids.length == 0 ){
			util.addErrorResponse( Messages.DATA_NOT_SELECT );
			return util;
		}

		for ( Integer id : ids ){
			Video bean = manager.findMyVideo( id, selfId, system );

			if( bean == null ){
				util.addErrorResponse( system ? Messages.DATA_NOT_EXIST : Messages.DATA_NOT_OPERATING );
				break;
			}
		}
		return util;
	}

	private WebErrors validateOUpdate( HttpServletRequest request, Integer id, Integer selfId, Boolean system ) {
		WebErrors errors = WebErrors.create( );

		if( id == null || id == 0 ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}

		Video bean = manager.findMyVideo( id, selfId, system );

		if( bean == null ){
			errors.addError( system ? Messages.DATA_NOT_EXIST : Messages.DATA_NOT_OPERATING );
			return errors;
		}

		return errors;

	}

	private WebErrors validateUpdate( HttpServletRequest request, Integer id ) {
		WebErrors errors = WebErrors.create( );

		if( id == null || id == 0 ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}

		Video bean = manager.findById( id );

		if( bean == null ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}

		return errors;

	}

	private WebErrors validateSave( Video bean ) {
		WebErrors errors = WebErrors.create( );

		return errors;
	}

	private WebErrors validateToSave( HttpServletRequest request ) {
		WebErrors errors = WebErrors.create( );
		AgentAndAdmins admin = TradeUtils.getAdmin( request );

		if( admin.getSystem( ) ){
			errors.addError( Messages.VIDEO_ADMIN_SYSTEM_MANAGER_NOT_TO_ADD );
		}
		return errors;
	}

	@Override
	protected String getDirectory( ) {
		return DIRECTORY;
	}

	@Autowired
	private FileRepository fileRepository;

	@Autowired
	private FlashSpiderService youku;

	@Autowired
	private VideoMng manager;

}
